package com.zenchn.shiro;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zenchn.entity.HttpResult;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * shiro 拒绝访问拦截器
 *
 * @author panbingqi
 * @date 2021-06-01
 */
@Component
public class MyFormAuthenticationFilter extends FormAuthenticationFilter {
    private static final Logger log = LoggerFactory.getLogger(MyFormAuthenticationFilter.class);

    /**
     * 所有请求都会经过的方法。
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {

        if (this.isLoginRequest(servletRequest, servletResponse)) {
            if (this.isLoginSubmission(servletRequest, servletResponse)) {
                if (log.isTraceEnabled()) {
                    log.trace("Login submission detected.  Attempting to execute login.");
                }
                return this.executeLogin(servletRequest, servletResponse);
            } else {
                //非登录请求，则返回请求未经授权相关信息.
                if (log.isTraceEnabled()) {
                    log.trace("Non login request, Returns unauthorized information.");
                }

                responseDetails(servletRequest, servletResponse);
                return false;

            }
        } else {
            //未登录，则返回请求未经授权相关信息.
            if (log.isTraceEnabled()) {
                log.trace("Unregistered, Returns unauthorized information.");
            }
            responseDetails(servletRequest, servletResponse);
            return false;
        }
    }

    private void responseDetails(ServletRequest servletRequest, ServletResponse servletResponse) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        HttpResult result = new HttpResult(request.getRequestURI());
        result.setMessage("HTTP 401 - 请求未经授权：账号未登录或token已过期.");
        result.setStatus(HttpStatus.UNAUTHORIZED.value());
        result.setError(HttpStatus.UNAUTHORIZED.getReasonPhrase());
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            PrintWriter out = response.getWriter();
            out.write(objectMapper.writeValueAsString(result));
            out.flush();
            out.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
